// pages/daily-check/daily-check.js
import request from '../../utils/request';
import { CHECKIN_REWARDS } from '../../utils/constants';

Page({
  data: {
    userInfo: {},
    checkinDays: 0,
    lastCheckin: null,
    canCheckin: false,
    rewards: CHECKIN_REWARDS,
    checkinAnimation: null,
    showConfetti: false
  },

  onLoad: function (options) {
    // 创建动画实例
    this.checkinAnimation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease'
    });
  },

  onShow: function () {
    // 获取用户信息
    const app = getApp();
    if (app.globalData.userInfo) {
      // 检查今天是否已经签到
      const lastCheckin = app.globalData.userInfo.lastCheckin;
      let canCheckin = true;

      if (lastCheckin) {
        const lastDate = new Date(lastCheckin);
        const today = new Date();
        
        // 如果最后签到时间是今天，则不能再次签到
        if (lastDate.getFullYear() === today.getFullYear() &&
            lastDate.getMonth() === today.getMonth() &&
            lastDate.getDate() === today.getDate()) {
          canCheckin = false;
        }
      }

      // 更新全局状态
      app.globalData.canCheckin = canCheckin;

      this.setData({
        userInfo: app.globalData.userInfo,
        checkinDays: app.globalData.userInfo.checkinDays || 0,
        lastCheckin: app.globalData.userInfo.lastCheckin,
        canCheckin: canCheckin  // 使用计算后的签到状态
      });
    }
  },
  
  // 签到功能
handleCheckIn: function() {
  // 显示加载中
  wx.showLoading({
    title: '签到中...',
    mask: true
  });
  const app = getApp();

   // 计算当天应得的积分
   const dayIndex = (this.data.checkinDays % 7);  // 获取今天是第几天（0-6）
   const todayScore = this.data.rewards[dayIndex].score;  // 获取对应的积分
  // 调用签到接口
  request({
    url: '/checkin',
    method: 'POST',
    data: {
      openId: app.globalData.userInfo.openId,
      score: todayScore  // 添加积分参数
    }
  })
  .then(response => {
    // 隐藏加载中
    wx.hideLoading();

    if (response.code === 0) {
      const { checkinDays, lastCheckin, score } = response.data;
      
      // 获取当天的奖励分数
      const dayIndex = (checkinDays - 1) % 7;  // 使用模运算确保索引在0-6之间
      const reward = this.data.rewards[dayIndex];
      
      // 更新全局用户信息
      app.globalData.userInfo.checkinDays = checkinDays;
      app.globalData.userInfo.lastCheckin = lastCheckin;
      app.globalData.userInfo.score = score;
      app.globalData.canCheckin = false;
      
      // 更新页面数据
      this.setData({
        userInfo: app.globalData.userInfo,
        checkinDays: checkinDays,
        lastCheckin: lastCheckin,
        canCheckin: false,
        showConfetti: true
      });
      
      // 执行签到动画
      this.playCheckinAnimation(checkinDays - 1);
      
      // 显示签到成功提示
      wx.showToast({
        title: `签到成功，获得${reward.score}积分`,
        icon: 'none',
        duration: 2000
      });
      
      // 3秒后隐藏彩带效果
      setTimeout(() => {
        this.setData({
          showConfetti: false
        });
      }, 3000);
    } else {
      throw new Error(response.message || '签到失败');
    }
  })
  .catch(err => {
    wx.hideLoading();
    console.error('签到失败:', err);
    wx.showToast({
      title: err.message || '签到失败，请重试',
      icon: 'none'
    });
  });
},
  // 执行签到
  doCheckin: function() {
    if (!this.data.canCheckin) {
      wx.showToast({
        title: '今天已经签到过了',
        icon: 'none'
      });
      return;
    }
    
    // 计算连续签到天数和奖励
    let checkinDays = this.data.checkinDays;
    let lastCheckin = this.data.lastCheckin;
    const today = new Date();
    
    // 检查是否是连续签到
    if (lastCheckin) {
      const lastDate = new Date(lastCheckin);
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      
      // 如果上次签到是昨天，则连续签到天数+1，否则重置为1
      if (lastDate.getFullYear() === yesterday.getFullYear() &&
          lastDate.getMonth() === yesterday.getMonth() &&
          lastDate.getDate() === yesterday.getDate()) {
        checkinDays += 1;
      } else {
        checkinDays = 1;
      }
    } else {
      checkinDays = 1;
    }
    // 如果连续签到超过7天，重置为1
    if (checkinDays > 7) {
      checkinDays = 1;
    }
    // 更新用户签到信息
    this.handleCheckIn()
  },
  
  // 播放签到动画
  playCheckinAnimation: function(index) {
    this.checkinAnimation.scale(1.2).step();
    this.checkinAnimation.scale(1.0).step();
    
    this.setData({
      checkinAnimation: this.checkinAnimation.export()
    });
  },
  
  // 返回上一页
  navigateBack: function() {
    wx.navigateBack();
  }
});